<template>

  <el-card class="box-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="addTrademark">添加</el-button>
      </div>
    </template>
    <el-table :data="trademarkList" border style="width: 100%" class="trademark-table"
      v-loading="loading">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称" flex="1" />
      <el-table-column prop="id" label="品牌LOGO" flex="1">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" class="trademark_logo">
        </template>
      </el-table-column>
      <el-table-column label="操作" flex="1" prop="id">
        <template v-slot="{ row }">
          <el-button type="warning" :icon="Edit" size="small"
            @click="updateTrademark(row)"></el-button>
          <el-button type="danger" :icon="Delete" size="small"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <div class="pagination-">
        <el-pagination class="pagination" v-model:current-page="currentPage"
          v-model:page-size="pageSize" layout=" prev, pager, next,jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <el-pagination class="pagination" v-model:current-page="currentPage"
          :page-sizes="[3, 6, 9, 12]" v-model:page-size="pageSize" layout=" sizes,total"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="dialogTableVisible" title="添加品牌" width="800px">
      <el-form label-width="100px" ref="ruleFormRef" :rules="rules" :model="ruleForm">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="ruleForm.tmName" placeholder="请输入品牌" class="trademark__input" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="imgUrl">
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" accept="image/*">
            <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过250Kb</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Trademark",
}

</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue"
import { ref, reactive } from 'vue'
import { getTrademarkListApi, delTrademarkItemApi, addTrademarkItemApi, updateTrademarkApi } from "@/api/product/trademark";
import type { UploadProps } from 'element-plus'
import { ElMessage, FormRules, FormInstance } from 'element-plus'

import { onMounted } from "vue";
import { TrademarkList } from "@/api/product/model/trademarkModel";


// 修改品牌
const updateTrademark = (row: any) => {
  dialogTableVisible.value = true;
  console.log(row);
  ruleForm.imgUrl = row.logoUrl;
  ruleForm.tmName = row.tmName;
  ruleForm.id = row.id;



}

//删除品牌

const delTrademarkItem = () => {
  console.log();

}


const loading = ref(false)

//表单校验按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.id) {
        updateTrademarkApi(ruleForm.id, ruleForm.imgUrl, ruleForm.tmName)
      } else {

        addTrademarkItemApi(ruleForm.imgUrl, ruleForm.tmName)
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        dialogTableVisible.value = false;
        getTrademarkList();
      }
    } else {
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    }
  })
}

//添加按钮
const addTrademark = () => {
  dialogTableVisible.value = true;
  //重置表单
  ruleFormRef.value?.resetFields()
}

const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 18, message: '长度在2-18', trigger: 'blur' }
  ],
  imgUrl: { required: true, message: '请上传图片' }
})

const ruleForm = reactive({
  id: 0,
  tmName: '',
  imgUrl: ''
})

const ruleFormRef = ref<FormInstance>()

const BASE_URL = import.meta.env.VITE_API_URL;


const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.imgUrl = response.data;
  ruleFormRef.value?.clearValidate(["imgUrl"])
}

//图片校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const fileTypes = ["image/jpeg", "image/png"]
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error('图片类型出错')
    return false
  } else if (rawFile.size / 1024 > 250) {
    ElMessage.error('图片大小超过250KB')
    return false
  }
  return true
}


const dialogTableVisible = ref(false)

const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)

const trademarkList = ref<TrademarkList>([])

const getTrademarkList = async () => {
  loading.value = true
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  total.value = res.total;
  trademarkList.value = res.records;
  loading.value = false
}


const handleSizeChange = (val: number) => {
  getTrademarkList()
}
const handleCurrentChange = (val: number) => {
  getTrademarkList()
}

onMounted(() => {
  getTrademarkList()
})

</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trademark-table {
  display: flex;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
  display: flex;
}

.demo-pagination-block .demonstration {
  display: flex;
  margin-bottom: 16px;
}

.pagination {
  float: left;
}

.pagination- {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.trademark_logo {
  width: 250px;
}

.trademark__input {
  width: 600px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>